<template>
  <div class="login-container">
    
    <div class="login-box">
      <div class="login-left">
        <div class="welcome-container">
          <h1 class="welcome-title">欢迎回来</h1>
          <p class="welcome-subtitle">请登录您的账户</p>
          <div class="login-image">
            <img src="../img/xiaohuangr.jpg" alt="Login Illustration">
          </div>
        </div>
      </div>
      
      <div class="login-right">
        <div class="form-container">
          <div class="logo">
            <img src="../img/love.jpg" alt="System Logo">
            <h2>管理系统</h2>
          </div>
          
          <el-form

            @submit.prevent="handleLogin"
          >
            <!-- 用户名登录 -->
            <el-form-item prop="username" v-if="loginMethod === 'username'">
              <el-input
                v-model="loginForm.username"
                placeholder="请输入用户名"
                prefix-icon="User"
                size="large"
              />
            </el-form-item>
            
            <!-- 手机号登录 -->
            <el-form-item prop="phone" v-if="loginMethod === 'phone'">
              <el-input
                v-model="loginForm.phone"
                placeholder="请输入手机号"
                prefix-icon="Phone"
                size="large"
              />
            </el-form-item>
            
            <!-- 邮箱登录 -->
            <el-form-item prop="email" v-if="loginMethod === 'email'">
              <el-input
                v-model="loginForm.email"
                placeholder="请输入邮箱"
                prefix-icon="Message"
                size="large"
              />
            </el-form-item>
            
            <!-- 密码登录 -->
            <el-form-item prop="password" v-if="loginMethod === 'username'">
              <el-input
                v-model="loginForm.password"
                type="password"
                placeholder="请输入密码"
                prefix-icon="Lock"
                size="large"
                show-password
                @keyup.enter="handleLogin"
              />
            </el-form-item>
            
            <!-- 验证码登录（手机/邮箱） -->
            <el-form-item prop="verificationCode" v-if="loginMethod !== 'username'">
              <el-input
                v-model="loginForm.verificationCode"
                :placeholder="`请输入${loginMethod === 'phone' ? '短信' : '邮箱'}验证码`"
                prefix-icon="Key"
                size="large"
              >
                <template #append>
                  <el-button 
                    :disabled="isCountingDown"
                    @click="getVerificationCode"
                  >
                    {{ countdown > 0 ? `${countdown}秒后重试` : '获取验证码' }}
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
            
            <div class="form-options">
              <el-checkbox v-model="loginForm.remember" v-if="loginMethod === 'username'">记住我</el-checkbox>
              <el-link type="primary" underline="never" @click="gotopassword">忘记密码?</el-link>
              <el-link type="primary" underline="never" @click="gotouser">还没用户?前往注册</el-link>
            </div>
            
            <el-form-item>
              <el-button
                type="primary"
                size="large"
                class="login-button"
                :loading="loading"
                native-type="submit"
              >
                {{ loginMethod === 'username' ? '登 录' : '验证码登录' }}
              </el-button>
            </el-form-item>
          </el-form>
          
          <div class="other-login">
            <el-divider>其他登录方式</el-divider>
            <div class="login-methods">
              <el-button circle @click="setLoginMethod('username')">
                <el-icon><Avatar /></el-icon>
              </el-button>
              <el-button circle @click="setLoginMethod('phone')">
                <el-icon><Phone /></el-icon>
              </el-button>
              <el-button circle @click="setLoginMethod('email')">
                <el-icon><Message /></el-icon>
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <div class="footer">
      <p>© 我从来没想过我会这样做</p>
      <p>从来没爱过所以爱错</p>
    </div>
  </div>
</template>

<script setup>

import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { Avatar, Message, Phone } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { getApiUrl } from '../config/api.js'

const router = useRouter()

// 检查是否已登录，如果已登录则跳转到仪表盘
const checkLoginStatus = () => {
  const token = localStorage.getItem('token')
  if (token) {
    router.push('/dashboard')
  }
}

// 在组件挂载时检查登录状态
checkLoginStatus()

const loginMethod = ref('username') // 'username' | 'phone' | 'email'
const isCountingDown = ref(false)
const countdown = ref(0)

// 记住我功能：自动填充用户名
const REMEMBER_KEY = 'rememberedUsername'
let loginForm = ref({
  username: localStorage.getItem(REMEMBER_KEY) || '',
  password: '',
  phone: '',
  email: '',
  verificationCode: '',
  remember: !!localStorage.getItem(REMEMBER_KEY)
})

let loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 4, message: '用户名长度不能小于4个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  verificationCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: '验证码为6位数字', trigger: 'blur' }
  ]
}

// 设置登录方式
const setLoginMethod = (method) => {
  loginMethod.value = method;
  if (method === 'username' && localStorage.getItem(REMEMBER_KEY)) {
    loginForm.value = {
      username: localStorage.getItem(REMEMBER_KEY),
      password: '',
      phone: '',
      email: '',
      verificationCode: '',
      remember: true
    }
  } else {
    loginForm.value = {
      username: '',
      password: '',
      phone: '',
      email: '',
      verificationCode: '',
      remember: false
    }
  }
};

// 获取验证码
const getVerificationCode = () => {
  if (loginMethod.value === 'phone' && !loginForm.value.phone) {
    ElMessage.warning('请输入手机号')
    return
  }
  
  if (loginMethod.value === 'email' && !loginForm.value.email) {
    ElMessage.warning('请输入邮箱')
    return
  }
  
  // 模拟发送验证码
  isCountingDown.value = true
  countdown.value = 60
  
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
      isCountingDown.value = false
    }
  }, 1000)
  
  ElMessage.success(`验证码已发送到您的${loginMethod.value === 'phone' ? '手机' : '邮箱'}`)
}

const gotopassword = () => {
  router.push('/Gotopassword')
}

const gotouser = () => {
  router.push('/Gotouser')
}

const loading = ref(false)
// 登录错误次数
const loginErrorCount = ref(0)

const handleLogin = async () => {
  loading.value = true
  let isValid = true
  if (loginMethod.value === 'username') {
    if (!loginForm.value.username || !loginForm.value.password) {
      ElMessage.warning('请填写用户名和密码')
      isValid = false
    }
  } else {
    if ((loginMethod.value === 'phone' && !loginForm.value.phone) || 
        (loginMethod.value === 'email' && !loginForm.value.email) || 
        !loginForm.value.verificationCode) {
      ElMessage.warning(`请填写${loginMethod.value === 'phone' ? '手机号' : '邮箱'}和验证码`)
      isValid = false
    }
  }
  if (!isValid) {
    loading.value = false
    return
  }

  if (loginMethod.value === 'username') {
    try {
      // 调用后端登录接口
      const res = await axios.post(getApiUrl('/auth/login'), {
        username: loginForm.value.username,
        password: loginForm.value.password
      }, {
        headers: { 'Content-Type': 'application/json' }
      })
      // 登录成功
      if (loginForm.value.remember) {
        localStorage.setItem(REMEMBER_KEY, loginForm.value.username)
      } else {
        localStorage.removeItem(REMEMBER_KEY)
      }
      // 写入token
      if (res.data && res.data.token) {
        localStorage.setItem('token', res.data.token)
      }
      loginErrorCount.value = 0
      loading.value = false
      ElMessage.success('登录成功')
      localStorage.setItem('loginUsername', loginForm.value.username)
      router.push('/dashboard')
    } catch (e) {
      loginErrorCount.value++
      loading.value = false
      if (loginErrorCount.value >= 5) {
        ElMessage.error('错误次数过多，请稍后再试')
        return
      } else {
        ElMessage.error('用户名或密码错误')
        return
      }
    }
  } else {
    loading.value = false
    ElMessage.error('暂仅支持用户名密码登录')
  }
}
</script>

<style scoped>
.login-container {
  width: 100%;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #f8fafc;
  padding: 20px;
  box-sizing: border-box;
}

.login-box {
  width: 100%;
  max-width: 1200px;
  min-height: 550px;
  display: flex;
  background: white;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.login-left {
  width: 50%;
  background: linear-gradient(135deg, #4f46e5, #7c3aed);
  color: white;
  padding: 50px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.welcome-title {
  font-size: 28px;
  font-weight: 600;
  margin-bottom: 10px;
}

.welcome-subtitle {
  font-size: 16px;
  color: rgba(255, 255, 255, 0.8);
  margin-bottom: 40px;
}

.login-image img {
  width: 320px;
  height: 350px;
  max-width: 100%;
  height: auto;
}

.login-right {
  width: 55%;
  padding: 60px 50px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.logo {
  text-align: center;
  margin-bottom: 40px;
}

.logo img {
  height: 50px;
  margin-bottom: 15px;
}

.logo h2 {
  font-size: 22px;
  color: #333;
  font-weight: 600;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
}

.login-button {
  width: 100%;
  font-size: 16px;
  letter-spacing: 2px;
  height: 48px;
}

.other-login {
  margin-top: 40px;
}

.login-methods {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 20px;
}

.footer {
  margin-top: 30px;
  text-align: center;
  color: #64748b;
  font-size: 14px;
}

.footer p {
  margin: 5px 0;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .login-box {
    max-width: 900px;
    min-height: 500px;
  }
  
  .login-left {
    padding: 40px 30px;
  }
  
  .login-right {
    padding: 50px 40px;
  }
  
  .welcome-title {
    font-size: 24px;
  }
  
  .login-image img {
    width: 280px;
  }
}

@media (max-width: 768px) {
  .login-container {
    padding: 10px;
    min-height: calc(100vh - 20px);
  }
  
  .login-box {
    flex-direction: column;
    min-height: auto;
    max-width: 100%;
  }
  
  .login-left {
    width: 100%;
    padding: 30px 20px;
    order: 2;
  }
  
  .login-right {
    width: 100%;
    padding: 40px 30px;
    order: 1;
  }
  
  .welcome-title {
    font-size: 20px;
  }
  
  .login-image img {
    width: 200px;
  }
  
  .logo h2 {
    font-size: 18px;
  }
}

@media (max-width: 480px) {
  .login-container {
    padding: 5px;
    min-height: calc(100vh - 10px);
  }
  
  .login-left {
    padding: 20px 15px;
  }
  
  .login-right {
    padding: 30px 20px;
  }
  
  .welcome-title {
    font-size: 18px;
  }
  
  .welcome-subtitle {
    font-size: 14px;
  }
  
  .login-image img {
    width: 150px;
  }
  
  .logo h2 {
    font-size: 16px;
  }
  
  .form-options {
    flex-direction: column;
    gap: 10px;
  }
}

/* 当F12开发者工具打开时的特殊处理 */
@media (max-height: 600px) {
  .login-container {
    min-height: auto;
    height: auto;
    padding: 10px;
  }
  
  .login-box {
    min-height: auto;
  }
  
  .login-left {
    padding: 20px 15px;
  }
  
  .login-right {
    padding: 25px 20px;
  }
  
  .welcome-title {
    font-size: 18px;
    margin-bottom: 5px;
  }
  
  .welcome-subtitle {
    font-size: 12px;
    margin-bottom: 20px;
  }
  
  .login-image img {
    width: 120px;
  }
}

/* 确保在小屏幕上表单元素也能正常显示 */
@media (max-width: 400px) {
  .login-left {
    padding: 15px 10px;
  }
  
  .login-right {
    padding: 20px 15px;
  }
  
  .welcome-title {
    font-size: 16px;
  }
  
  .logo h2 {
    font-size: 14px;
  }
}
</style>